/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Portions created by the Initial Developer are
 * Copyright (C) 2012 the Initial Developer.
 * All Rights Reserved.
 *
 * The Original Code is "http://semi-frame.googlecode.com/svn/trenk/".
 *
 * The Initial Developer of the Original Code is the author below.
 */
/**
 * @file FileUtil.cpp
 * @brief Utility of file.
 * @author mornongcloud
 * @date 2011/03/11
 */

#include "semi/util/FileUtil.h"

namespace semi {
namespace util {

FileUtil::FileUtil() {
}

FileUtil::~FileUtil() {
}

Strings FileUtil::getFilePaths(std::string path) {

    Strings ret;

    DIR *dir;
    struct dirent *dp;

    if ((dir = opendir(path.c_str())) == NULL)
        return ret;

    Strings::iterator ite = ret.begin();

    if (path.c_str()[path.length() - 1] != '/')
        path = path + "/";

    for (dp = readdir(dir); dp != NULL; dp = readdir(dir)) {
        ret.insert(ite, path + std::string(dp->d_name));
    }
    closedir(dir);
}

bool FileUtil::copy(std::string path1, std::string path2) {

    FILE *fp1 = fopen(path1.c_str(), "rb");
    if (fp1 == NULL) {
        // std::cout << "error fopen path1" << std::endl;
        return false;
    }

    FILE *fp2 = fopen(path2.c_str(), "wt");
    if (fp2 == NULL) {
        // std::cout << "error fopen path2" << std::endl;
        return false;
    }

    char buf[8];
    int siz = sizeof(buf);
    while (fread(&buf, siz, 1, fp1) == 1) {
        //        if (feof(fp1) != NULL)
        //            break;
        // std::cout << buf;

        fwrite(&buf, siz, 1, fp2);
    }
    // std::cout << std::endl;

    bool ret = true;
    if (fclose(fp1) == EOF)
        ret = false;

    if (fclose(fp2) == EOF)
        ret = false;

    return ret;
}
}

}
